<template>
  <vxe-modal
    v-model="dialogFormVisible"
    :title="title"
    show-footer
    transfer
    width="600"
    destroy-on-close
    @close="close"
  >
    <template #default>
      <el-upload
        ref="uploadRef"
        v-model:file-list="fileList"
        :action="'/system/user/import?updateSupport=' + updateSupport"
        :auto-upload="false"
        :disabled="formLoading"
        :headers="uploadHeaders"
        :limit="1"
        :on-error="submitFormError"
        :on-exceed="handleExceed"
        :on-success="submitFormSuccess"
        accept=".xlsx, .xls"
        drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="updateSupport" />
              是否更新已经存在的用户数据
            </div>
            <span>仅允许导入 xls、xlsx 格式文件。</span>
            <el-link
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              type="primary"
              @click="importTemplate"
            >
              下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
    </template>
    <template #footer>
      <el-button type="primary" :loading="formLoading" @click="submitForm">
        <i class="iconfont-fw ri-upload-2-line" />
        {{ translate('上传') }}
      </el-button>
      <el-button type="danger" plain @click="close()">
        <i class="iconfont-fw ri-upload-2-line" />
        {{ translate('取消') }}
      </el-button>
    </template>
  </vxe-modal>
</template>

<script>
  import { useUserStore } from '@/store/modules/user'
  import * as UserApi from '@/api/system/user'
  import download from '@/utils/download'
  import { translate } from '@/i18n'

  export default defineComponent({
    name: 'ImpUser',
    components: {},
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const $XEUtils = inject('$XEUtils')
      const $baseLodash = inject('$baseLodash')
      const userStore = useUserStore()
      const state = reactive({
        importUrl: '',
        uploadRef: null,
        uploadHeaders: {},
        updateSupport: false,
        fileList: [],
        formLoading: false,
        title: '',
        dialogFormVisible: false,
      })

      const showEdit = () => {
        state.dialogFormVisible = true
        state.title = translate('用户导入')
      }

      /** 提交表单 */
      const submitForm = async () => {
        if (state.fileList.length == 0) {
          $baseMessage(
            translate('请上传文件'),
            'error',
            'vab-hey-message-success'
          )
          return
        }
        // 提交请求
        state.uploadHeaders = {
          Authorization: `Bearer ${userStore.accessTokenKey}`,
          'tenant-id': userStore.tenantId,
        }
        state.formLoading = true
        state['uploadRef'].submit()
      }

      const submitFormSuccess = (response) => {
        if (response.code !== 0) {
          $baseMessage(
            translate(response.msg),
            'error',
            'vab-hey-message-success'
          )
          state.formLoading = false
          return
        }
        // 拼接提示语
        const data = response.data
        let text = `上传成功数量：${data.createUsernames.length};`
        for (const username of data.createUsernames) {
          text += `< ${username} >`
        }
        text += `更新成功数量：${data.updateUsernames.length};`
        for (const username of data.updateUsernames) {
          text += `< ${username} >`
        }
        text += `更新失败数量：${Object.keys(data.failureUsernames).length};`
        for (const username in data.failureUsernames) {
          text += `< ${username}: ${data.failureUsernames[username]} >`
        }
        $baseMessage(translate(text), 'error', 'vab-hey-message-success')
        // 发送操作成功的事件
        emits('success')
      }

      /** 上传错误提示 */
      const submitFormError = () => {
        $baseMessage(
          translate('上传失败，请您重新上传！'),
          'error',
          'vab-hey-message-success'
        )
        state.formLoading = false
      }

      /** 重置表单 */
      const resetForm = () => {
        // 重置上传状态和文件
        state.formLoading = false
        state.uploadRef?.clearFiles()
      }

      /** 文件数超出提示 */
      const handleExceed = () => {
        $baseMessage(
          translate('最多只能上传一个文件！'),
          'error',
          'vab-hey-message-success'
        )
      }

      /** 下载模板操作 */
      const importTemplate = async () => {
        const res = await UserApi.importUserTemplate()
        download.excel(res, '用户导入模版.xls')
      }
      const close = () => {
        emit('fetch-data')
        state.dialogFormVisible = false
      }

      return {
        ...toRefs(state),
        showEdit,
        importTemplate,
        handleExceed,
        close,
        submitForm,
        resetForm,
        submitFormSuccess,
        submitFormError,
        translate,
      }
    },
  })
</script>
<style lang="scss" scoped>
  .el-tabs__new-tab {
    border: 0px !important;

    div {
      margin-right: 40px;
    }
  }
</style>
